﻿/// <reference path="_namespace.js" />
/// <reference path="../lang/extensions.js" />

/*****************************************************************************
Ajax library. Kevin Robinson 2006.
Bootstrapper (2 of 2) file containing ContentLoader class only. 
/*****************************************************************************/

ajax.lang.addNamespace("ajax.net");

ajax.net.READY_STATE_UNINITIALIZED = 0;
ajax.net.READY_STATE_LOADING       = 1;
ajax.net.READY_STATE_LOADED        = 2;
ajax.net.READY_STATE_INTERACTIVE   = 3;
ajax.net.READY_STATE_COMPLETE      = 4;

//-----------------------------------------------------------------------------
ajax.net.ContentLoader = function(client, onload, onerror, url, method, requestParams, async) // Constructor
{
    this.client     = client;
    this.url        = url;
    this.method     = (method) ? method : "GET";
    this.requestParams  = requestParams || [];
    
    this.onload     = onload;
    this.onerror    = (onerror) ? onerror : this.defaultError;
    this.async      = (typeof(async) == "undefined") ?  true: async;
    this.date       = "none";
}

//-----------------------------------------------------------------------------
ajax.net.ContentLoader.prototype = 
{
    getTransport: function()
    {
        var transport = null;
        var xmlHttp = null;
        
        try
        {
            xmlHttp = XMLHttpRequest;
        }
        catch(ex)
        {}
        
        if (xmlHttp)
        {
            transport = new XMLHttpRequest();
        }        
        else if (ActiveXObject)
        {
            try
            {
                transport = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e)
            {
                transport = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return transport;
    },
    sendRequest: function()
    {
        var requestParams = [];
		var logs = ajax.debug.Output;
		
        for (var i = 0; i < arguments.length; i++)
            requestParams.push(arguments[i]);
        
        var request = this.getTransport();
        if (this.method.toUpperCase() == "GET")
            request.open(this.method, this.url + "?" + this.queryString(requestParams), this.async); 
        else
            request.open(this.method, this.url, this.async);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        
        // Wrap the responder in a callback
        var loader = this;
        request.onreadystatechange = function()
        { 
            // Call our handler, passing OUR OWN context
            loader.handleAjaxResponse.call(loader, request);
        };
        
        // Log the time of this
        this.date = new Date();		
		logs.writeLn("HTTP Output: " + this.url + "    parms: " + this.queryString(requestParams));		
        request.send(this.queryString(requestParams));
        // In case of synchronous request...return the request object
        return request;
    },
    queryString: function(args)
    {
        var requestParams = [];
        
        // Add state data
        for (var i = 0; i < this.requestParams.length; i++)
            requestParams.push(this.requestParams[i]);
        
        // Add argument data
        for (var i = 0; i < args.length; i++)
            requestParams.push(args[i]);
        
        var queryString = "";
        if (requestParams && requestParams.length > 0)
        {
            for (var i = 0; i < requestParams.length; i++)
                queryString += requestParams[i] + "&";
            
            // Take off the trailing & sign
            queryString = queryString.substring(0, queryString.length - 1);
        }
        return queryString;
    },
    handleAjaxResponse: function(request)
    {         
        // Called from context of ContentLoader object instance        
        if (request.readyState == ajax.net.READY_STATE_COMPLETE)
        {                        
            var contentLength = request.getResponseHeader("Content-Length");
            var kb = parseInt(contentLength)/1024;
            ajax.net.ContentLoader.totalKilobytes += kb;
            
			var logs = ajax.debug.Output;
            var now = new Date();
            var diff = now - this.date;
			logs.writeLn("HTTP Input:: completed taking " + diff + " milliseconds.");
			logs.writeLn("File size: " + kb + " K, Total: " + ajax.net.ContentLoader.totalKilobytes + " K");
            if (this.isSuccess(request))
            {
                // Call the onload in the components's own context
                if (this.onload)
                    this.onload.call(this.client, request);
            }
            else
            {                
                this.onerror.call(this.client, request);
            }
        }        
    },
    isSuccess: function(request)
    {
        return request.status == 0 || (request.status >= 200 && request.status < 300);
    },
    defaultError: function(req)
    {
		var logs = ajax.debug.Output;
		
		// Important: Called in context of this.client!
		logs.writeLn("Error fetching data!"
		+ "\n\nreadyState: " + req.readyState
		+ "\nstatus: " + req.status
		+ "\nheaders: " + req.getAllResponseHeaders()
		+ "\nbody: " + req.responseText);	
    },
    toString: function(){ return "ajax.net.ContentLoader"; }
    
};

// Statics
//-----------------------------------------------------------------------------
ajax.net.ContentLoader.alertHttpError = function(res)
{// Alerts status and message   
    var message = ajax.net.ContentLoader.getHttpErrorMessage(res);
    alert("Error Code: " + res.status + "\n\nStatus: " + res.statusText + "\n\nDescription: " + message);
}

//-----------------------------------------------------------------------------
ajax.net.ContentLoader.alertHttpErrorMessage = function(res)
{// Alerts message only    
    var message = ajax.net.ContentLoader.getHttpErrorMessage(res);
    alert(message);
}

ajax.net.ContentLoader.getHttpErrorMessage = function(res)
{
    var ele = document.createElement("div");
    ele.innerHTML = res.responseText;
    var text = ele.innerText ? ele.innerText : ele.innerHTML;
    var textParts = text.split("]");
    text = textParts[textParts.length-1];
    textParts = text.split("/");
    text = textParts[0];
    
    if (text == "")
        text = "Error (" + res.status + ")"; // If no text returned
            
    return text;
}

ajax.net.ContentLoader.totalKilobytes = 0;
//-----------------------------------------------------------------------------